#!/usr/bin/python3
# -*- coding: utf-8 -*-

"""
# @version: v1.0
# @author : cd
# @Email : 19688513@qq.com
# @Project : horizons-engine-pybroker
# @File : ThrottleController.py
# @Software: PyCharm
# @time: 2025/6/17 15:00
# @description : 
"""

import urllib3
import logging

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
# 禁用不安全的请求警告
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)


class ThrottleController:
    """智能请求节流控制器（单线程版）"""
    def __init__(self):
        self.request_count = 0
        self.last_reset = time.time()
        self.interval_config = [
            (50, 0.1),    # 前50次请求间隔0.1秒
            (200, 0.5),   # 50-250次间隔0.5秒
            (500, 1.0),   # 250-750次间隔1秒
            (float('inf'), 2.0)  # 超过750次间隔2秒
        ]

    def get_delay(self):
        """动态计算请求间隔"""
        self.request_count += 1
        current_time = time.time()
        elapsed = current_time - self.last_reset

        # 每60秒重置计数器
        if elapsed > 60:
            self.request_count = 0
            self.last_reset = current_time

        for threshold, delay in self.interval_config:
            if self.request_count <= threshold:
                return delay
        return self.interval_config[-1][1]
